

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:huajianshe_app/base/BaseState.dart';
import 'package:huajianshe_app/base/NetworkManager.dart';
import 'package:huajianshe_app/base/Refresher.dart';
import 'package:huajianshe_app/common/res.dart';
import 'package:huajianshe_app/network/Api.dart';
import 'package:huajianshe_app/widget/appbar/CAppBar.dart';

import 'LessonItem.dart';
import 'model/LessonModel.dart';

class LessonListPage extends StatefulWidget {
  
  final MyLessonType type;

  const LessonListPage(this.type, {Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _LessonListPageState();
  }
}

class _LessonListPageState extends BaseState<LessonListPage> {

  int page = 1;
  
  @override
  void initState() {
    super.initState();
    refresher = Refresher<Lesson>(this);
    load(false);
  }

  load(bool doNotShowProgressBar) {
    var data = {
      'list_rows': 10,
      'page': page,
    };
    NetworkParams api = widget.type == MyLessonType.buy ? Api.lessonBuyed() : Api.lessonFavority();
    sendReq(api, LessonListResp(), data: data, doNotShowProgressBar: doNotShowProgressBar);
  }

  @override
  void onRefresh() {
    refresher?.mode = Mode.refresh;
    page = 1;
    load(true);
  }

  @override
  void onLoadMore() {
    refresher?.mode = Mode.loadMore;
    load(true);
  }

  @override
  void onReqSuccess<T>(T t, int code, String msg, String path) {
    if (t is LessonListResp) {
      // lessons = t.data?.data;
      refresher?.load(t.data?.data);
      setState(() => null);
    }
  }

  @override
  Widget build(BuildContext context) {
    return
      Padding(padding: EdgeInsets.symmetric(vertical: 13),
          child: refresher?.build(buildChild())
      );
  }

  Widget? buildChild() {
    print('buildChild');
    Widget? child = buildEmptyPage();
    if (child != null) {
      print('empty buildChild');
      return child;
    }
    return
      Padding(padding: EdgeInsets.symmetric(vertical: 13), child:
        ListView.separated(
          itemBuilder: (_, index) {
            return Padding(padding: EdgeInsets.symmetric(horizontal: 13),
                child: LessonItem(refresher?.data?[index]));
          },
          separatorBuilder: (_, index) => H(15),
          itemCount: (refresher?.data?.length ?? 0)
        )
      );
  }
}

enum MyLessonType {
  buy, favorite
}